package com.tencent.qplus.paddata.stat;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Calendar;

import com.tencent.qplus.paddata.db.DataSourceManager;
import com.tencent.qplus.paddata.util.JdbcUtils;

/**
 * 删除历史数据，只保留70天数据，以保证数据库速度
 * @author shiangzhang
 *
 */
public class DeleteHistoryDataJob extends Job {
	
	private Calendar cl = Calendar.getInstance();
	private int dayOfMonth = cl.get(Calendar.DAY_OF_MONTH);
	
	//删除paddata.uinlogin_x
	private void deletPaddataUuinlogin_x(){
		Connection conn = null;
		Statement st = null;
		try {
			conn = DataSourceManager.getInstance().getDataSource("paddatadb").getConnection();
			st = conn.createStatement();
			String pre70Day = dateUtils.getDateStrByDaysFromDate(statDate, -70);
			for(int i=0;i<100;i++){
				if(i%30==dayOfMonth%30){
					String sql = "delete from uinlogin_"+i+" where logindate<'"+pre70Day+"'";
					st.executeUpdate(sql);
					logger.info(sql);
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}finally{
			JdbcUtils.release(st);
			JdbcUtils.release(conn);
		}
	}
	
	
	//删除padversiondatadb.uinlogin_x
	private void deletPadversiondataUuinlogin_x(){
		Connection conn = null;
		Statement st = null;
		try {
			conn = DataSourceManager.getInstance().getDataSource("padversiondatadb").getConnection();
			st = conn.createStatement();
			String pre70Day = dateUtils.getDateStrByDaysFromDate(statDate, -70);
			for(int i=0;i<100;i++){
				if(i%30==dayOfMonth%30){
					String sql = "delete from padversiondatadb.uinlogin_"+i+" where logindate<'"+pre70Day+"'";
					st.executeUpdate(sql);
					logger.info(sql);
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}finally{
			JdbcUtils.release(st);
			JdbcUtils.release(conn);
		}
	}
	
	//删除paddata.userinfo_x
	private void deletPaddataUserinfo_x(){
		Connection conn = null;
		Statement st = null;
		try {
			conn = DataSourceManager.getInstance().getDataSource("paddatadb").getConnection();
			st = conn.createStatement();
			String pre70Day = dateUtils.getDateStrByDaysFromDate(statDate, -70);
			for(int i=0;i<100;i++){
				if(i%30==dayOfMonth%30){
					String sql = "delete from userinfo_"+i+" where logindate<'"+pre70Day+"'";
					st.executeUpdate(sql);
					logger.info(sql);
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}finally{
			JdbcUtils.release(st);
			JdbcUtils.release(conn);
		}
	}

	@Override
	public void run() {
		deletPaddataUuinlogin_x();
		deletPaddataUserinfo_x();
		deletPadversiondataUuinlogin_x();
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DeleteHistoryDataJob job = new DeleteHistoryDataJob();
		job.stat(args);
	}

}
